<template>
    <div class="goods-add-form">
        <div class="section">
            <h2 class="section-title">基础信息</h2>
            <el-form ref="ruleFormRef" style="max-width: 1200px;margin: 20px;" :model="finished_goods_store" status-icon
                :rules="rules" label-width="auto" class="demo-ruleForm">
                <div style="display: flex; justify-content: space-between;">
                    <div style="width: 48%;">
                        <el-form-item label="成品入库编号" style="margin-bottom: 30px;">
                            <el-input v-model="finished_goods_store.finished_goods_store_code" placeholder="自动获取编号"
                                disabled />
                        </el-form-item>
                        <el-form-item prop="warehouse_code" label="入库仓库" style="margin-bottom: 30px;">
                            <el-select v-model="finished_goods_store.warehouse_code" placeholder="请选择入库仓库"
                                @change="handleSelectChange">
                                <el-option v-for="item in Weahouse" :key="item.warehouse_code"
                                    :label="item.warehouse_name" :value="item.warehouse_code" />
                            </el-select>
                        </el-form-item>
                        <el-form-item prop="finished_goods_store_dept_id" label="入库部门" style="margin-bottom: 30px;">
                            <el-tree-select v-model="finished_goods_store.finished_goods_store_dept_id"
                                :data="deptOptions" :props="defaultProps" :check-strictly="true" placeholder="请选择入库部门"
                                @change="getUser()">
                                <template #header>
                                    <el-input v-model="deptName" placeholder="搜索入库部门" style="padding: 5px"
                                        @input="getDeptDebounced" />
                                </template>
                            </el-tree-select>
                        </el-form-item>
                    </div>

                    <div style="width: 48%;">
                        <el-form-item label="入库日期" style="margin-bottom: 30px;" prop="finished_goods_store_time">
                            <el-date-picker v-model="finished_goods_store.finished_goods_store_time" type="date" :editable="false"
                                placeholder="请选择入库日期" :size="size" style="width: 480px;"
                                value-format="YYYY-MM-DDTHH:mm:ss.SSSZ" />
                        </el-form-item>
                        <el-form-item prop="zone_code" label="入库库区" style="margin-bottom: 30px;">
                            <el-select v-model="finished_goods_store.zone_code" placeholder="请选择入库库区"
                                @change="handleSzone">
                                <el-option v-for="item in Warhouse_zone" :key="item.zone_code" :label="item.zone_name"
                                    :value="item.zone_code" />
                            </el-select>
                        </el-form-item>
                        <el-form-item prop="finished_goods_store_rep_id" label="入库员" style="margin-bottom: 30px;">
                            <el-select v-model="finished_goods_store.finished_goods_store_rep_id" placeholder="请选择入库员">
                                <template #header>
                                    <el-input v-model="userName" placeholder="搜索入库员" style="padding: 5px"
                                        @input="getUserDebounced" />
                                </template>
                                <el-option v-for="item in userOptions" :key="item.user_id" :label="item.user_name"
                                    :value="item.user_id" />
                            </el-select>
                        </el-form-item>
                    </div>
                </div>
            </el-form>
        </div>

        <div class="section">
            <h2 class="section-title">入库产品明细</h2>
            <div style="float: left;margin: 10px 0px;">
                <el-button type="primary" @click="productAdd">添加</el-button>
                <el-button @click="productDel">移除</el-button>
            </div>
            <el-table :data="selectedData" border style="width: 100%" :cell-style="{ textAlign: 'center' }"
                :header-cell-style="{
                    textAlign: 'center',
                    background: '#f5f7fa',
                    fontWeight: 'bold',
                    position: 'sticky',
                    top: 0
                }" ref="selectedTable" @selection-change="handleSelectedChange">
                <el-table-column type="selection" width="55" />
                <el-table-column prop="pro_name" label="产品名称" />
                <el-table-column prop="pro_code" label="产品编号" width="160" />
                <el-table-column prop="pro_brand" label="品牌" />
                <el-table-column prop="pro_model" label="规格型号" />
                <el-table-column prop="measure_id" label="单位">
                    <template #default="scope">
                        <span>{{ measureValue(scope.row.measure_id) }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="address" label="成品数量">
                    <template #default="scope">
                        <el-input v-model="scope.row.finished_goods_qty" style="width: 75px" :precision="2" :min="0" />
                    </template>
                </el-table-column>
                <el-table-column prop="address" label="不合格数量">
                    <template #default="scope">
                        <el-input v-model="scope.row.unqualified_qty" style="width: 75px" :precision="2" :min="0" />
                    </template>
                </el-table-column>
                <el-table-column prop="address" label="入库数量">
                    <template #default="scope">
                        <el-input v-model="scope.row.store_qty" style="width: 75px" :precision="2" :min="0" readonly />
                    </template>
                </el-table-column>
                <el-table-column prop="address" label="出库库位">
                    <template #default="scope">
                        <el-select v-model="scope.row.location_code" placeholder="选择库位" size="small"
                            @change="(val) => handleLocationChange(val, scope.row)">
                            <el-option v-for="item in Warehouse_location" :key="item.location_code"
                                :label="item.location_name" :value="item.location_code" />
                        </el-select>
                    </template>
                </el-table-column>
            </el-table>
            <div style="height: 40px; line-height: 40px;">
                <div style="display: inline-block; float: left;">合计</div>
                <div style="display: inline-block; float:right">成品总数量：{{ finished_goods_total_qty }} &nbsp;&nbsp;&nbsp;
                    不合格总数量：{{
                        unqualified_total_qty }} &nbsp;&nbsp;&nbsp;入库总数量：{{
                        store_total_qty }}&nbsp;&nbsp;&nbsp;质检状态：{{ finished_goods_store.quality_testing_status == '0' ?
                        "不合格"
                        : finished_goods_store.quality_testing_status == '1' ? "部分合格" : "全部合格"
                    }}
                </div>
            </div>
        </div>

        <div class="button-group" style="position: absolute; bottom: 10px; right: 64px; display: flex; gap: 10px;">
            <el-button type="primary" @click="handleAdd">保存</el-button>
            <el-button @click="handleClose">关闭</el-button>
        </div>
    </div>

    <el-dialog v-model="proSaleTableVisible" width="930" title="添加成品信息">
        <hr>
        <div style="margin: 10px 0px;">
            <div style="float: left;margin: 10px 0px;">
                <el-input v-model="proCode" style="width: 240px;margin-right: 20px;" placeholder="请输入产品名称/编号" />
                <el-tree-select v-model="proTypeCode" :data="proTypeOptions" placeholder="请选择产品类型" :props="treeProps"
                    clearable check-strictly style="width: 240px">
                    <template #header>
                        <el-input v-model="proTypeName" placeholder="搜索产品类型" style="padding: 5px"
                            @input="getProTypeDebounced" />
                    </template>
                </el-tree-select>
            </div>
            <div style="float: right;margin: 10px 0px;">
                <el-button @click="proReaslt">重置</el-button>
                <el-button type="primary" @click="proEedit">
                    查询
                </el-button>
            </div>
        </div>
        <el-table ref="multipleTableRef" :data="productData" :cell-style="{ textAlign: 'center' }" :header-cell-style="{
            textAlign: 'center',
            background: '#f5f7fa',
            fontWeight: 'bold',
            position: 'sticky',
            top: 0
        }" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" :selectable="isDisabled" />
            <el-table-column property="pro_code" label="产品编号" width="180" />
            <el-table-column property="pro_name" label="产品名称" width="200" />
            <el-table-column property="pro_model" label="规格型号" />
            <el-table-column property="measure_id" label="单位">
                <template #default="scope">
                    <span>{{ measureValue(scope.row.measure_id) }}</span>
                </template>
            </el-table-column>
            <el-table-column property="pro_cost_price" label="入库单价" />
            <el-table-column property="pro_type_code" label="产品类型">
                <template #default="scope">
                    <span>{{ typeValue(scope.row) }}</span>
                </template>
            </el-table-column>
        </el-table>
        <br>
        <div style="text-align: center;display: flex; justify-content: center;">
            <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5, 10, 20, 50]"
                :small="false" :background="true" layout="total, sizes, prev, pager, next, jumper" :total="pageCount"
                @size-change="handleSizeChange" @current-change="handleCurrentChange" size="small" />
        </div>
        <hr>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="handleConfirmColse">取消</el-button>
                <el-button type="primary" @click="handleConfirmSelection">
                    确定
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script>
import { ref, reactive, onMounted, inject, watch, toRaw } from 'vue'
import dayjs from 'dayjs'
import axios from 'axios'
import { useRouter } from 'vue-router';
import { useStore } from 'vuex';
import { ElMessage,ElLoading } from 'element-plus';
import { debounce } from 'lodash';
export default {
    setup() {
        const finished_goods_store = reactive({
            finished_goods_store_id: 0,//成品入库主键
            finished_goods_store_code: "",//成品入库编号
            warehouse_code: "",//出库仓库编号
            warehouse_name: "",//出库仓库名称
            zone_code: "",//出库库区编号
            zone_name: "",//出库库区名称
            location_code: "",//出库库位编号
            location_name: "",//出库库位编号
            finished_goods_store_rep_id: "",//入库员id
            finished_goods_store_dept_id: "",//入库员部门
            finished_goods_store_time: "",//入库时间
            quality_testing_status: "",//质检状态
        })
        const router = useRouter()
        const Weahouse = ref([]);//仓库信息
        const Warhouse_zone = ref([]);//库区信息
        const Warehouse_location = ref([])//库位信息
        const deptOptions = ref([])
        const userOptions = ref([])
        const deptName = ref('')
        const userName = ref('')
        const proSaleTableVisible = ref(false)
        const productData = ref([])
        const currentPage = ref(1)
        const pageSize = ref(5)
        const pageCount = ref(0)
        const measureOptios = ref([])
        const proTypeOptions = ref([])
        const proCode = ref('')
        const proTypeCode = ref('')
        const proTypeName = ref('')
        const multipleTableRef = ref(null); // 表格引用
        const selectedProducts = ref([]); // 存储选中的产品
        const selectedTable = ref(null);//表格引用
        const selectedRows = ref([]);//存储选中的数据
        const selectedData = ref([]); // 最终确认选择的数据
        const finished_goods_total_qty = ref(0)//记录成品总数量
        const unqualified_total_qty = ref(0)//记录不合格总数量
        const store_total_qty = ref(0)//记录入库总数量
        const store = useStore()
        const code = store.state.FinishedGoodsStoreCode
        const ruleFormRef = ref(null)
        const rules = reactive({
            finished_goods_store_time: [
                { required: true, message: "入库日期不能为空", trigger: ['blur', 'change'] },
            ], warehouse_code: [
                { required: true, message: "入库仓库不能为空", trigger: ['blur', 'change'] },
            ], zone_code: [
                { required: true, message: "入库库区不能为空", trigger: ['blur', 'change'] },
            ], finished_goods_store_dept_id: [
                { required: true, message: "入库部门不能为空", trigger: ['blur', 'change'] },
            ], finished_goods_store_rep_id: [
                { required: true, message: "入库员不能为空", trigger: ['blur', 'change'] },
            ]
        });

        onMounted(async () => {
            getMeasure()
            getDept()
            getProType()
            await WeahousesSelect()
            await finishedGoodsStoreFill()
        })

        watch(selectedData, (newVal) => {
            //每次计算时清空累加
            finished_goods_total_qty.value = 0
            unqualified_total_qty.value = 0
            store_total_qty.value = 0
            finished_goods_store.quality_testing_status = ""
            newVal.forEach(row => {
                //验证成品数量
                if (isNaN(Number(row.finished_goods_qty))) {
                    ElMessage.warning('销售数量必须是数字');
                    row.finished_goods_qty = 0;
                }

                // 验证不合格数量
                if (isNaN(Number(row.unqualified_qty))) {
                    ElMessage.warning('销售单价必须是数字');
                    row.unqualified_qty = 0;
                }

                //验证入库数量
                if (isNaN(Number(row.store_qty))) {
                    ElMessage.warning('销售单价必须是数字');
                    row.store_qty = 0;
                }

                //验证不合格数量输入是否正确
                if (Number(row.unqualified_qty) > Number(row.finished_goods_qty)) {
                    ElMessage.warning('请输入正确的不合格数量');
                    row.unqualified_qty = 0;
                }

                row.store_qty = Number(row.finished_goods_qty) - Number(row.unqualified_qty)
                finished_goods_total_qty.value += Number(row.finished_goods_qty)
                unqualified_total_qty.value += Number(row.unqualified_qty)
                store_total_qty.value += Number(row.store_qty)
            });
            //验证质检状态
            if (unqualified_total_qty.value == finished_goods_total_qty.value)
                finished_goods_store.quality_testing_status = '0'//不合格
            else if (unqualified_total_qty.value == 0)
                finished_goods_store.quality_testing_status = '2'//全部合格
            else if (unqualified_total_qty.value < finished_goods_total_qty.value)
                finished_goods_store.quality_testing_status = '1'//部分合格
        }, { deep: true });


        async function finishedGoodsStoreFill() {
            try {
                const result = await axios.get("http://localhost:5181/api/FG_Finished_Goods_Store/GetFG_Finished_Goods_StoreByCode", {
                    params: {
                        code: code
                    }
                })
                for (const key in finished_goods_store) {
                    // 排除数字类型字段（如 user_id、dept_id）
                    if (key === 'finished_goods_store_rep_id' || key === 'finished_goods_store_dept_id') {
                        finished_goods_store[key] = Number(result.data[key]); // 保留数字类型
                    } else if (key === 'finished_goods_store_time') {
                        finished_goods_store[key] = new Date(result.data[key]).toISOString();
                    } else {
                        finished_goods_store[key] = String(result.data[key]); // 其他字段转字符串
                    }
                }
                console.info(finished_goods_store)
                getUser()
                await handleSelectChange(finished_goods_store.warehouse_code)

                await handleSzone(finished_goods_store.zone_code)

                await finishedGoodsStoreDetailsFill()
            } catch (error) {
                console.info(error)
            }
        }

        async function finishedGoodsStoreDetailsFill() {
            const result = await axios.get("http://localhost:5181/api/FG_Finished_Goods_Store/Get_Finished_Goods_Store_DetailsByCode", {
                params: { code: code }
            })
            selectedData.value = result.data.map(item => ({
                location_code: item.location_code,
                location_name: item.location_name,
                ...item,
            }))
        }

        // 查询仓库信息
        async function WeahousesSelect() {
            try {
                const result = await axios.get("http://localhost:5181/api/Db_warehouse/WarehouseBySelect", {
                    headers: { authorization: `Bearer ${localStorage.getItem('token')}` }
                });
                Weahouse.value = result.data;
                console.info(Weahouse.value)
            } catch (err) {
                console.info(err)
            }
        }

        // 选择入库仓库事件触发
        const handleSelectChange = async (selectedValue) => {
            try {
                const selectedItem = Weahouse.value.find(item => item.warehouse_code === selectedValue);
                finished_goods_store.warehouse_name = selectedItem?.warehouse_name || "";

                const result = await axios.get("http://localhost:5181/api/Db_warehouse_zone/warehouse_zone", {
                    params: { warehouse_code: selectedValue },
                    headers: { authorization: `Bearer ${localStorage.getItem('token')}` }
                });

                Warhouse_zone.value = result.data;
            } catch (err) {
                console.error("加载库区失败:", err);
                ElMessage.warning("仓库对应的库区加载失败");
            }
        };

        //选择入库库位时触发
        const handleSzone = async (value) => {
            try {
                const selectedItemzone = Warhouse_zone.value.find(item => item.zone_code == value);
                finished_goods_store.zone_name = selectedItemzone?.zone_name || "";

                const result = await axios.get("http://localhost:5181/api/Db_warehouse_location/warehouse_location", {
                    params: { zone_code: value },
                    headers: { authorization: `Bearer ${localStorage.getItem('token')}` }
                });

                Warehouse_location.value = result.data;
            } catch (err) {
                console.error("加载库位失败:", err);
                ElMessage.warning("库区对应的库位加载失败");
            }
        }

        const handleLocationChange = (value, row) => {
            // 找到选中的库位
            const selectedLocation = Warehouse_location.value.find(item => item.location_code == value);
            // 更新当前行的库位信息
            if (selectedLocation) {
                row.location_code = selectedLocation.location_code;
                row.location_name = selectedLocation.location_name;
            } else {
                row.location_code = "";
                row.location_name = "";
            }
        };

        //查询计量单位
        function getMeasure() {
            axios.get("http://localhost:5181/api/Dict/Get_Dict_Datas", {
                params: {
                    dict_type: "db_measure"
                }, headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                measureOptios.value = result.data
                measureOptios.value = [{
                    dict_value: "0", dict_label: "请选择单位"
                }, ...result.data]
            }).catch((err) => {
                console.info(err)
            });
        }

        //根据计量单位id返回计量单位名称
        function measureValue(row) {
            if (!row) return "无";
            const parentDept = measureOptios.value.find((sex) => sex.dict_value == row);
            return parentDept ? parentDept.dict_label : "无";
        }

        //防抖函数0.5秒后进行查询
        const getDeptDebounced = debounce(getDept, 500);
        function getDept() {
            axios.get("http://localhost:5181/api/Dept/Get_Dept_Trees", {
                params: {
                    name: deptName.value
                },
                headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                deptOptions.value = convertToTreeOptions(result.data)
            }).catch((err) => {
                console.info(err)
            });
        }

        const getUserDebounced = debounce(getUser, 500);
        function getUser() {
            axios.get("http://localhost:5181/api/User/GetUsers", {
                params: {
                    dept: finished_goods_store.finished_goods_store_dept_id,
                    name: userName.value
                },
                headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                userOptions.value = result.data
            }).catch((err) => {
                console.info(err)
            });
        }

        //把二维数据转换为结构数据
        const convertToTreeOptions = (items) => {
            return items.map(item => ({
                value: item.dept_id,
                label: item.dept_name,
                children: item.children && item.children.length > 0
                    ? convertToTreeOptions(item.children)
                    : []
            }))
        }

        const getProTypeDebounced = debounce(getProType, 500);
        function getProType() {
            axios.get("http://localhost:5181/api/Product_Type/GetProduct_Types", {
                params: {
                    currentPage: 0,
                    pageSize: 0,
                    typeName: proTypeName.value,
                    status: '0'
                }, headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                proTypeOptions.value = convertToTreeProTypeOptions(result.data)
            }).catch((err) => {
                console.info(err)
            });
        }

        const convertToTreeProTypeOptions = (items) => {
            return items.map(item => ({
                value: item.pro_type_code,
                pro_type_code: item.pro_type_code,
                label: item.pro_type_name,
                children: item.children && item.children.length > 0
                    ? convertToTreeProTypeOptions(item.children)
                    : []
            }))
        }

        //根据产品类型编号查询出产品类型名称
        function typeValue(row) {
            if (!row || !proTypeOptions.value) return "无"; // 空值保护

            // 假设 row 是一个对象，包含 pro_type_code 字段
            const typeCode = row.pro_type_code;
            // 递归查找匹配的项
            const findLabel = (items) => {
                for (const item of items) {
                    if (item.pro_type_code === typeCode) {
                        return item.label;
                    }
                    if (item.children && item.children.length > 0) {
                        const found = findLabel(item.children);
                        if (found) return found;
                    }
                }
                return null;
            };

            const label = findLabel(proTypeOptions.value);
            return label || "未知类型"; // 如果没找到返回默认值
        }

        function productAdd() {
            proSaleTableVisible.value = true
            proFill()
            proCount()
        }

        function proFill() {
            axios.get("http://localhost:5181/api/Db_Product/Get_Products", {
                params: {
                    proName: proCode.value,
                    typeCode: proTypeCode.value,
                    currentPage: currentPage.value,
                    pageSize: pageSize.value
                },
                headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                console.info(result.data)
                productData.value = result.data
            }).catch((err) => {
                console.info(err)
            });
        }

        function proCount() {
            axios.get("http://localhost:5181/api/Db_Product/ProductCount", {
                params: {
                    proName: proCode.value,
                    typeCode: proTypeCode.value,
                }, headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                console.info(result.data)
                pageCount.value = result.data
            }).catch((err) => {
                console.info(err)
            });
        }

        function handleSizeChange(val) {
            pageSize.value = val;
            proFill();
        }

        function handleCurrentChange(val) {
            currentPage.value = val;
            proFill();
        }

        //查询按钮
        function proEedit() {
            proFill()
            proCount()
        }

        //重置按钮
        function proReaslt() {
            proCode.value = ""
            proTypeCode.value = ""
            proFill()
            proCount()
        }

        //关闭按钮
        function handleConfirmColse() {
            proSaleTableVisible.value = false
            proCode.value = ""
            proTypeCode.value = ""
        }

        // 表格选择变化时的处理函数
        const handleSelectionChange = (val) => {
            selectedProducts.value = val;
        };

        //点击确定存储选择的产品数据
        const handleConfirmSelection = () => {
            selectedData.value = [...selectedData.value, ...selectedProducts.value.map(item => ({
                ...item,
                finished_goods_qty: 0,
                unqualified_qty: 0,
                store_qty: 0,
                location_code: ""
            }))]//保存选择的产品数据
            proSaleTableVisible.value = false
            multipleTableRef.value.clearSelection()//清空当前选择
        }

        //表格选择变化时处理数据
        const handleSelectedChange = (val) => {
            selectedRows.value = val;
        };

        //判断以添加过的产品数据不能再次添加
        const isDisabled = (row) => {
            return !selectedData.value.some(item => item.pro_code === row.pro_code);
        };

        //移除选中的table控件数据
        const productDel = () => {
            if (selectedRows.value.length === 0) {
                ElMessage.warning('请先选择要移除的数据');
                return;
            }

            const selectedCodes = selectedRows.value.map(item => item.pro_code);
            selectedData.value = selectedData.value.filter(
                item => !selectedCodes.includes(item.pro_code)
            );

            if (selectedTable.value) {
                selectedTable.value.clearSelection();
            }

            selectedRows.value = [];
        };

        const validateLocations = () => {
            return selectedData.value.every(item => {
                return item.location_code && item.location_name;
            });
        };


        function handleAdd() {
            ruleFormRef.value.validate(async (valid, fields) => {
                if (valid) {
                    if (selectedData.value.length > 0) {
                        if (validateLocations()) {
                            obtainCode().then(() => {
                                finished_goods_storeAdd()
                            }).catch((err) => {
                                console.info(err)
                            });
                        } else {
                            ElMessage.warning('请为所有产品选择库位');
                            return;
                        }
                    } else {
                        ElMessage.warning('请选择要添加的产品数据');
                        return;
                    }
                }
            })
        }

        function obtainCode() {
            return axios.get("http://localhost:5181/api/DJBH/DJBH", {
                params: {
                    en_code: 17
                }
            }).then((result) => {
                finished_goods_store.finished_goods_store_code = result.data
            }).catch((err) => {
                console.info(err)
            });
        }

        function finished_goods_storeAdd() {
            const loadingInstance = ElLoading.service({
                lock: true,
                text: '正在修改中...',
                background: 'rgba(0, 0, 0, 0.7)',
            });
            const FG_Finished_Goods_Store_DetailsAddDto = selectedData.value.map(item => ({
                finished_goods_store_id: item.finished_goods_store_id,
                finished_goods_store_code: item.finished_goods_store_code,
                finished_goods_store_details_id: item.finished_goods_store_details_id,
                pro_name: item.pro_name,
                pro_code: item.pro_code,
                pro_brand: item.pro_brand,
                pro_model: item.pro_model,
                measure_id: item.measure_id,
                finished_goods_qty: item.finished_goods_qty,
                unqualified_qty: item.unqualified_qty,
                store_qty: item.store_qty,
                location_code: item.location_code,
                location_name: item.location_name
            }))
            const finishedGoodsStoreDetailsUpdateDto = {
                fG_Finished_Goods_StoreUpdateDto: {
                    finished_goods_store_id: finished_goods_store.finished_goods_store_id,
                    quality_testing_status: finished_goods_store.quality_testing_status,
                    quality_testing_by: localStorage.getItem('userLName'),
                    quality_testing_time: dayjs().format('YYYY-MM-DDTHH:mm:ss.SSSZ'),
                    finished_goods_store_rep_id: finished_goods_store.finished_goods_store_rep_id,
                    finished_goods_store_dept_id: finished_goods_store.finished_goods_store_dept_id,
                    finished_goods_store_time: finished_goods_store.finished_goods_store_time,
                    warehouse_code: finished_goods_store.warehouse_code,
                    warehouse_name: finished_goods_store.warehouse_name,
                    zone_code: finished_goods_store.zone_code,
                    zone_name: finished_goods_store.zone_name,
                    update_by: localStorage.getItem('userLName'),
                    update_time: dayjs().format('YYYY-MM-DDTHH:mm:ss.SSSZ'),
                },
                fG_Finished_Goods_Store_Details: [...FG_Finished_Goods_Store_DetailsAddDto]
            }
            axios.put("http://localhost:5181/api/FG_Finished_Goods_Store/FG_Finished_Goods_StoreUpdate", finishedGoodsStoreDetailsUpdateDto, {
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                if (result.data > 0) {
                    ElMessage({
                        type: 'success',
                        message: '成品入库订单修改成功！'
                    });
                    handleClose()
                } else {
                    ElMessage({
                        type: 'danger',
                        message: '成品入库订单修改失败！'
                    });
                }
            }).catch((err) => {
                console.info(err)
            }).finally(() => {
                loadingInstance.close();
            })
        }

        const closeTab = inject('closeTab'); // 注入关闭方法
        function handleClose() {
            const targetPath = "/main/FG/FinishedGoodsStore";

            if (closeTab) {
                closeTab(); // 调用父组件提供的关闭方法
            }

            // 添加目标标签页（如果不存在）
            const tabs = inject('editableTabs');
            if (tabs && !tabs.value.some(tab => tab.path === targetPath)) {
                tabs.value.push({
                    title: "成品入库",
                    name: targetPath,
                    path: targetPath
                });
            }

            // 跳转并激活目标标签页
            const activeTab = inject('editableTabsValue');
            if (activeTab) {
                activeTab.value = targetPath;
            }

            router.push(targetPath);
        }

        return {
            finished_goods_store, handleSelectChange, handleSzone, handleLocationChange, Weahouse, Warehouse_location, Warhouse_zone,
            getDeptDebounced, getUserDebounced, deptOptions, userOptions, deptName, userName, getUser, proSaleTableVisible, productAdd,
            currentPage, pageSize, pageCount, productData, measureOptios, measureValue, proTypeOptions, proCode, proTypeCode, getProTypeDebounced,
            handleSizeChange, handleCurrentChange, proTypeName, typeValue, proEedit, proReaslt, handleConfirmColse, handleSelectionChange,
            handleConfirmSelection, handleSelectedChange, isDisabled, multipleTableRef, selectedProducts, selectedRows, selectedData, selectedTable,
            productDel, finished_goods_total_qty, unqualified_total_qty, store_total_qty, ruleFormRef, rules, handleAdd, validateLocations, handleClose
        }
    }
}
</script>

<style scoped>
.goods-add-form {
    padding: 20px;
    background-color: #fff;
}

.section {
    margin-bottom: 30px;
    border: 1px solid #ebeef5;
    border-radius: 4px;
    padding: 20px;
    /* 添加阴影效果 */
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.section-title {
    font-size: 16px;
    font-weight: bold;
    margin-bottom: 15px;
}

.button-group {
    float: right;
    display: flex;
    position: flex;
    text-align: right;
    margin-top: 20px;
    height: 7%;
    align-items: center;
    width: 80.1%;
    background-color: #ffffff;
    justify-content: flex-end;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
    padding-right: 20px;
}
</style>